package com.cn.hnust.service.impl;

import com.cn.hnust.dao.*;
import com.cn.hnust.pojo.*;
import com.cn.hnust.service.ArticleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @anther 龙泽国
 */
@Service("/articleService")
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleCategoryMapper articleCategoryMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private UserMapper userMapper;


    /**
     * 获取文章分类的一二、二三级的Map（工具方法）
     *
     * @param map
     * @return
     */
    public static Map<String, List> getMap(List<NM> map) {
        Map<String, List> map1 = new HashMap<String, List>();
        String n = "";
        int index = 0;
        List<String> list = new ArrayList<String>();
        for (NM nm : map) {
            if (n.equals("")) {
                n = nm.getN();
            }

            if (n.equals(nm.getN())) {
                list.add(nm.getM());
            } else {
                map1.put(n, list);
                list = new ArrayList<String>();
                n = nm.getN();
                list.add(nm.getM());
            }
            index++;
            if (index == map.size()) {
                map1.put(n, list);
            }
        }
        return map1;

    }


    /**
     * 查询某个用户已发布所有文章
     *
     * @param pageNum
     * @param pageSize
     * @param user
     * @return
     */
    public ResultInfo findUserArticle(Integer pageNum,
                                      Integer pageSize,
                                      User user) {
        PageInfo<Article> userPageInfo = null;
        ResultInfo resultInfo = new ResultInfo();
        try {
            //分页显示
            PageHelper.startPage(pageNum, pageSize);
            List<Article> articleList = articleMapper.findUserArticle(user);
            userPageInfo = new PageInfo<Article>(articleList);
            resultInfo.setData(userPageInfo);
            resultInfo.setFlag(true);
            return resultInfo;

        } catch (Exception e) {
            resultInfo.setFlag(false);
            return resultInfo;
        }
    }

    /**
     * 查询某个用户的草稿
     *
     * @param pageNum
     * @param pageSize
     * @param user
     * @return
     */
    public ResultInfo findUserDraft(int pageNum,
                                    int pageSize,
                                    User user) {
        PageInfo<Article> userPageInfo = null;
        ResultInfo resultInfo = new ResultInfo();
        try {
            //分页显示
            PageHelper.startPage(pageNum, pageSize);
            List<Article> articleList = articleMapper.findUserDraft(user);
            userPageInfo = new PageInfo<Article>(articleList);
            resultInfo.setData(userPageInfo);
            resultInfo.setFlag(true);
            return resultInfo;

        } catch (Exception e) {
            resultInfo.setFlag(false);
            return resultInfo;
        }
    }

    /**
     * 进入编辑博客
     *
     * @param article_id
     * @return
     */
    public ResultInfo intoEditArticle(Long article_id) {
        ResultInfo resultInfo = new ResultInfo();
        try {
            Article article = articleMapper.findArticleByArticleId(article_id);
            List<ArticleTag> articleTags = articleTagMapper.findArticleTagByArticleId(article_id);
            Category category = articleCategoryMapper.findCategoryByArticleId(article_id);
            List list1 = new ArrayList();
            List list = new ArrayList();
            for (ArticleTag articleTag : articleTags) {
                Tag tag = tagMapper.findByTagId(articleTag.getTag_id());
                list.add(tag);
            }
            list1.add(article);
            list1.add(category);
            list1.add(list);
            resultInfo.setData(list1);
            resultInfo.setFlag(true);
        } catch (Exception e) {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("获取失败！");
        }

        return resultInfo;
    }

    /**
     * 获取文章分类的一二、二三级and标签
     *
     * @return
     */
    public ResultInfo userWriteArticle() {
        ResultInfo resultInfo = new ResultInfo();
        Map<Object, Object> stringMapMap = null;
        try {
            Map<Object, Map<Object, Object>> mapMap = new HashMap<Object, Map<Object, Object>>();


            List<Tag> tags = tagMapper.findAllTag();
            //List<Category> categories = articleMapper.findAllCategory();


            List<NM> map12 = categoryMapper.findMap12();
            List<NM> map23 = categoryMapper.findMap23();
            Map<String, List> map1 = getMap(map12);
            Map<String, List> map2 = getMap(map23);
            Map<Object, Object> map = new HashMap<Object, Object>();
            Set<Map.Entry<String, List>> entries1 = map1.entrySet();
            Set<Map.Entry<String, List>> entries2 = map2.entrySet();
            for (Map.Entry<String, List> entry : entries1) {
                String key = entry.getKey();
                List value = entry.getValue();
                for (Object o : value) {
                    for (Map.Entry<String, List> stringListEntry : entries2) {
                        if (o.equals(stringListEntry.getKey())) {
                            map.put(o, stringListEntry.getValue());
                        }
                    }
                }
                mapMap.put(key, map);
                map = new HashMap<Object, Object>();
            }
            stringMapMap = new HashMap<Object, Object>();
            stringMapMap.put("categories", mapMap);
            stringMapMap.put("tags", tags);
            resultInfo.setFlag(true);
            resultInfo.setData(stringMapMap);
            return resultInfo;


        } catch (Exception e) {
            resultInfo.setFlag(false);
            return resultInfo;
        }


    }

    /**
     * 编辑并提交博客
     *
     * @param article
     * @param tags
     * @param category_name
     * @return
     */
    public ResultInfo saveEditArticle(Article article, List<String> tags, String category_name) {
        ResultInfo resultInfo = new ResultInfo();
        Date date = new Date();
        Article article1 = articleMapper.findArticleByArticleId(article.getArticle_id());


        try {
            //1为发布博客，0位存为草稿
            if (article.getArticle_status() == 1 && article1.getArticle_status() == 1) {//已发布----->发布
                article.setArticle_updatetime(date);
            } else if (article.getArticle_status() == 1 && article1.getArticle_status() == 0) {//草稿------>发布
                article.setArticle_updatetime(date);
                article.setArticle_createtime(date);
            } else if (article.getArticle_status() == 0 && article1.getArticle_status() == 0) {//草稿------->草稿
                article.setArticle_updatetime(date);
            }

            //修改博客or草稿
            articleMapper.updateArticleOrDraft(article);

            //删除标签、类型关系
            articleTagMapper.deleteArticleTag(article.getArticle_id());
            articleCategoryMapper.deleteArticleCategory(article.getArticle_id());
            //在article_category中建立关系
            Category category1 = categoryMapper.findByCategoryName(category_name);
            articleCategoryMapper.saveArticleAndCategory(article, category1);

            //在article_tag中建立关系
            for (String tagName : tags) {
                Tag tag1 = tagMapper.findByTagName(tagName);
                articleTagMapper.saveArticleAndTag(article, tag1);
            }
            resultInfo.setFlag(true);
        } catch (Exception e) {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("编辑失败!");
        }
        return resultInfo;
    }

    /**
     * 保存博客
     *
     * @param article
     * @param tags
     * @param category_name
     * @return
     */
    public ResultInfo userSaveArticle(Article article, List<String> tags, String category_name, User user) {
        ResultInfo resultInfo = new ResultInfo();
        Date date = new Date();
        try {

            if (article.getArticle_status() == 1) {//1为发布博客，0位存为草稿
                article.setArticle_updatetime(date);
                article.setArticle_createtime(date);
            } else {
                article.setArticle_updatetime(date);
            }
            //保存记录
            articleMapper.userSaveArticle(article, user);
            System.out.println("==============================");
            //通过时间查询   刚存入数据库的博客Article对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(date);
            System.out.println(format);
            //通过时间和user找博客
            Article article1 = articleMapper.findArticleByDate(format, user.getUid());

            //在article_category中建立关系
            Category category1 = categoryMapper.findByCategoryName(category_name);
            articleCategoryMapper.saveArticleAndCategory(article1, category1);


            //在article_tag中建立关系
            for (String tagName : tags) {
                Tag tag1 = tagMapper.findByTagName(tagName);
                articleTagMapper.saveArticleAndTag(article1, tag1);
            }

            resultInfo.setFlag(true);
            return resultInfo;
        } catch (Exception e) {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("发布失败！");
            return resultInfo;
        }

    }

    /**
     * 删除博客
     *
     * @param article_id
     */
    public ResultInfo userDeleteArticle(Long article_id) {
        ResultInfo resultInfo = new ResultInfo();
        try {
            articleMapper.delUserArticle(article_id);
            resultInfo.setFlag(true);
            resultInfo.setErrorMsg("删除成功！");
        } catch (Exception e) {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("删除失败！");
        }
        return resultInfo;
    }


    /**
     * 删除发表的博客到草稿箱里面
     *
     * @param article_id
     * @param uid
     * @return
     */
    public ResultInfo deletetorecyclebin(String article_id, String uid) {
        ResultInfo resultInfo = new ResultInfo();
        try {
            articleMapper.deletetorecyclebin(article_id, uid);
            resultInfo.setFlag(true);
            resultInfo.setErrorMsg("删除成功！");
        } catch (Exception e) {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("删除失败！");
        }
        return resultInfo;
    }


    /**
     * 查看博客详情
     *
     * @param article_id
     * @return
     */
    public ResultInfo viewArticle(Long article_id) {
        ResultInfo resultInfo = new ResultInfo();
//        try {
        Article article = articleMapper.findArticleByArticleId(article_id);
        User user = userMapper.findByUid(article.getUid());
        //找标签
        List<ArticleTag> articleTags = articleTagMapper.findArticleTagByArticleId(article_id);
        //找类型
        Category category = articleCategoryMapper.findCategoryByArticleId(article_id);
       /* //查找二级
        Category category1=articleCategoryMapper.findCategoryByPid(category.getCategory_pid());
        //查找以一级
        Category category2=articleCategoryMapper.findCategoryByPid(category1.getCategory_pid());
*/

        List list1 = new ArrayList();
        for (ArticleTag articleTag : articleTags) {
            articleTag.getTag_id();
            Tag tag = tagMapper.findByTagId(articleTag.getTag_id());
            list1.add(tag);
        }

        //浏览量+1
        articleMapper.updateArticleViewCount(article_id);
        List list = new ArrayList();
        list.add(article);
        list.add(user);
        list.add(list1);
        List list2 = new ArrayList();
        list2.add(category);
        /*list2.add(category1);
        list2.add(category2);*/

        list.add(list2);
        resultInfo.setFlag(true);
        resultInfo.setData(list);
//        } catch (Exception e) {
//            resultInfo.setFlag(false);
//            resultInfo.setErrorMsg("查看失败！");
//        }


        return resultInfo;
    }

    /**
     * 收藏博客
     *
     * @param article_id
     * @param uid
     * @return
     */
    public ResultInfo favoriteArticle(Long article_id, int uid) {
        ResultInfo resultInfo = new ResultInfo();
        try {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(date);
            //查找是否有相同的user_id和article_id
            Long isexistence = articleMapper.findByaidAnduid(article_id, uid);
            //判断是否有
            if (isexistence == null) {
                //不存在（第一次收藏）
                articleMapper.addfavoritearticle(article_id, uid, format);
                resultInfo.setFlag(true);
                resultInfo.setErrorMsg("收藏成功");
            } else {
                //存在则删除（再次点击）
                articleMapper.delfavoritearticle(isexistence);
                resultInfo.setFlag(true);
                resultInfo.setErrorMsg("取消收藏");

            }
        } catch (Exception e) {
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("收藏失败！");
        }

        return resultInfo;
    }


    /**
     * 点赞量操作
     * @param article_id
     * @param uid
     * @return
     */
    public ResultInfo likeCount(long article_id,int uid,String time) {
        ResultInfo resultInfo=new ResultInfo();

        //判断是否有点赞记录
        RealTimeLikes rtl = articleMapper.selectLikeRecord(article_id, uid);

        if(rtl!=null){
            //有点赞记录，则做取消点赞操作

            try {
                //减少文章点赞量
                articleMapper.deletelikeCount(article_id);

                //删除点赞记录
                articleMapper.deleteLikeRecord(article_id, uid);
                resultInfo.setFlag(true);
                resultInfo.setErrorMsg("取消点赞成功");

            }catch (Exception e){

                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("取消点赞失败");
            }
        }else {
            //无点赞记录，则做点赞操作
            rtl=new RealTimeLikes();

            try {
                //添加文章点赞量
                articleMapper.addlikeCount(article_id);

                //封装类
                rtl.setArticle_id(article_id);
                rtl.setLike_people_id(uid);
                rtl.setLike_time(time);

                //添加点赞记录
                articleMapper.addRealTimeLike(rtl);

                //获取被点赞的题目
                String title=articleMapper.selectTitleByArticleId(article_id);

                //获取点赞人
                String username=userMapper.findByUid(uid).getUsername();

                String message=username+"点赞了你的博文:"+title+"("+time+")";

                resultInfo.setFlag(true);
                resultInfo.setData(message);

            }catch (Exception e){
                e.printStackTrace();
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("点赞失败");
            }
        }

        return resultInfo;
    }
}
